const WebSocket = require('ws');

class BroadcastManager {
    constructor() {
        this.servers = new Map();
    }

    registerServer(path, server) {
        this.servers.set(path, server);
    }

    broadcast(path, data, filter = null) {
        const server = this.servers.get(path);
        if (!server) {
            console.warn(`未找到路径 ${path} 对应的服务器`);
            return;
        }

        server.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                if (filter && !filter(client)) {
                    return;
                }
                client.send(JSON.stringify(data));
            }
        });
    }

    broadcastToAll(data, filter = null) {
        this.servers.forEach((server, path) => {
            this.broadcast(path, data, filter);
        });
    }

    getConnectedClients(path) {
        const server = this.servers.get(path);
        if (!server) return [];

        const clients = [];
        server.clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                clients.push({
                    id: client.id,
                    wsType: client.wsType,
                    subscriptions: client.subscriptions ? Array.from(client.subscriptions) : [],
                    notificationTypes: client.notificationTypes ? Array.from(client.notificationTypes) : []
                });
            }
        });
        return clients;
    }

    getServerStats() {
        const stats = {};
        this.servers.forEach((server, path) => {
            let connectedCount = 0;
            server.clients.forEach(client => {
                if (client.readyState === WebSocket.OPEN) {
                    connectedCount++;
                }
            });
            stats[path] = {
                connectedClients: connectedCount,
                totalClients: server.clients.size
            };
        });
        return stats;
    }
}

module.exports = BroadcastManager;